import { NextRequest, NextResponse } from 'next/server'
import { getServerSession } from 'next-auth'
import { authOptions } from '@/lib/auth'
import prisma from '@/lib/prisma'

// 获取单个公告
export async function GET(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    const { id } = params

    const announcement = await prisma.announcement.findUnique({
      where: { id },
      include: {
        experiment: {
          select: {
            id: true,
            title: true,
            createdById: true,
          },
        },
      },
    })

    if (!announcement) {
      return NextResponse.json({ message: '公告不存在' }, { status: 404 })
    }

    return NextResponse.json({ announcement })
  } catch (error) {
    console.error('获取公告详情失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 更新公告
export async function PUT(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // 只有教师和管理员可以更新公告
    if (session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const { id } = params
    const { title, content } = await req.json()

    // 检查公告是否存在
    const announcement = await prisma.announcement.findUnique({
      where: { id },
      include: {
        experiment: true,
      },
    })

    if (!announcement) {
      return NextResponse.json({ message: '公告不存在' }, { status: 404 })
    }

    // 验证权限（只有创建实验的教师或管理员可以更新公告）
    if (
      session.user.role !== 'ADMIN' &&
      announcement.experiment.createdById !== session.user.id
    ) {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 更新公告
    const updatedAnnouncement = await prisma.announcement.update({
      where: { id },
      data: {
        title,
        content,
      },
    })

    return NextResponse.json({
      message: '公告更新成功',
      announcement: updatedAnnouncement,
    })
  } catch (error) {
    console.error('更新公告失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
}

// 删除公告
export async function DELETE(
  req: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const session = await getServerSession(authOptions)
    if (!session) {
      return NextResponse.json({ message: '未授权' }, { status: 401 })
    }

    // 只有教师和管理员可以删除公告
    if (session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    const { id } = params

    // 检查公告是否存在
    const announcement = await prisma.announcement.findUnique({
      where: { id },
      include: {
        experiment: true,
      },
    })

    if (!announcement) {
      return NextResponse.json({ message: '公告不存在' }, { status: 404 })
    }

    // 验证权限（只有创建实验的教师或管理员可以删除公告）
    if (
      session.user.role !== 'ADMIN' &&
      announcement.experiment.createdById !== session.user.id
    ) {
      return NextResponse.json({ message: '权限不足' }, { status: 403 })
    }

    // 删除公告
    await prisma.announcement.delete({
      where: { id },
    })

    return NextResponse.json({ message: '公告已删除' })
  } catch (error) {
    console.error('删除公告失败:', error)
    return NextResponse.json({ message: '服务器错误' }, { status: 500 })
  }
} 